#!/usr/bin/php5 -q
<?php

    $REPODIR = "pack/Cydia";
    $CATEGORY = "DevImpress";
    $VERSION = time();
    
    //
    // Make package
    //
    $d = dir(".");
    while (false !== ($e = $d->read())) {
	if(is_dir($e) && ".app" === substr($e, -4)) {
	    $app_name = substr($e, 0, strlen($e) - 4);	    
	}
    }
    $d->close();
    
    if(!isset($app_name)) die("Can't find application folder!");
    
    $app_lname = strtolower($app_name);

    // Make control file    
    $a = array();
    
    $a['bundle'] = "com.devimpress.".$app_lname;
    $a['appname'] = $app_name;
    $a['version'] = $VERSION; 
    $a['description'] = "Version " . $VERSION . " of " . $app_name; 
    
    $f = explode("@", implode("", file("pack/_control")));
    $r = fopen($REPODIR . "/" . $app_lname . "/DEBIAN/control", "w+");
    foreach($f as $fi) {
	if(isset($a[$fi])) fputs($r, $a[$fi]);
	else fputs($r, $fi);
    }
    fclose($r);

    // Copy application files
    system("rm -r -f ".$REPODIR."/".$app_lname."/Applications/".$app_name.".app");
    system("cp -r ".$app_name.".app ".$REPODIR."/".$app_lname."/Applications/");

    // Clear svn data
    system("rm -r -f ".$REPODIR."/".$app_lname."/Applications/".$app_name.".app/.svn");
    system("rm -r -f ".$REPODIR."/".$app_lname."/Applications/".$app_name.".app/English.lproj/.svn");
    system("rm -r -f ".$REPODIR."/".$app_lname."/Applications/".$app_name.".app/Russian.lproj/.svn");
    
    // Build package and Packages file
    system("rm -f ".$REPODIR."/".$app_lname.".deb");
    system("rm -f ".$REPODIR."/Packages");

    chdir($REPODIR);

    system("dpkg -b ".$app_lname."");
    system("dpkg-scanpackages -m . /dev/null >Packages ");
    system("bzip2 Packages");
    
    chdir("../..");        
?>
